package com.leave.mos.service.impl;

import com.leave.mos.constant.TablenameConstant;
import com.leave.mos.entity.QueryParam;
import com.leave.mos.service.find.QueryAggregateService;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @ClassName QueryAggregateServiceImpl
 * @Description TODO
 * @Author lh
 * @Date 2021/7/9 16:50
 * @Version 1.0
 *      $addFields 输出包含输入文档中所有现有字段和新添加字段的文档. (所有 + 新的)
 *      $project   明确指定输入文档中所有现有字段并添加新字段的阶段。(指定现有的 + 新的)
 *
 *  聚合取值的方式
 **/
@Service
public class QueryAggregateServiceImpl implements QueryAggregateService {


    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public List<Map> sum(QueryParam queryParam){

        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where(TablenameConstant.Order.goodsNum).is(queryParam.getGoodsNum())),
                Aggregation.project("zoneId","price")
                        //重命名字段的名字
                        .and("price").as("price2").andInclude("total"),
                Aggregation.group("zoneId").sum("price").as("total"),
                Aggregation.sort(Sort.by(Sort.Direction.DESC,"total")),
                Aggregation.project("zoneId","total")
        );
        AggregationResults<Map> aggregate = mongoTemplate.aggregate(aggregation, TablenameConstant.Order.TableName, Map.class);
        List<Map> maps = aggregate.getMappedResults();
        return maps;
    }



}
